package com.spring.demo.rabbit.config;

import com.spring.demo.rabbit.ExchangeConst;
import com.spring.demo.rabbit.QueueConst;
import com.spring.demo.rabbit.RoutingKeyConst;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/***
 * @title RelayExchangeConfig
 * @description: 延迟消息 ： 通过rabbitmq_delayed_message_exchange插件实现延迟队列
 * @author baiji
 * @version 1.0.0
 * @create 2023/9/7 11:33
 **/
@Configuration
public class RelayExchangeConfig {

    /**
     * 声明延迟交换器
     * 定义一个类型为“x-delayed-message”交换机，这个类型不是RabbitMQ默认的那几种交换机类型之一，而是通过插件安装的。
     * 然后，通过“x-delayed-type” 参数指定该交换机的类型是direct类型。
     *
     * @return
     */
    @Bean("delayExchange")
    public CustomExchange delayExchange() {
        HashMap<String, Object> args = new HashMap<>(1);
        args.put("x-delayed-type", "direct");
        return new CustomExchange(ExchangeConst.DELAY_EXCHANGE, "x-delayed-message", false, false, args);
    }

    /**
     * 声明延迟队列
     *
     * @return
     */
    @Bean("delayedQueue")
    public Queue customQueue() {
        return QueueBuilder.durable(QueueConst.DELAY_QUEUE).build();
    }

    /**
     * 声明延迟队列和延迟交换器的绑定关系
     *
     * @param queue
     * @param exchange
     * @return
     */
    @Bean("delayedBinding")
    public Binding delayedBinding(@Qualifier("delayedQueue") Queue queue, @Qualifier("delayExchange") CustomExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(RoutingKeyConst.DELAY_ROUTING_KEY).noargs();
    }
}
